package com.xinshujia.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.xinshujia.entity.ResourceEntity;
import com.xinshujia.response.RespResult;
import com.xinshujia.service.ResourceService;
import com.xinshujia.utils.GsonUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-15 19:39       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 *     资源控制器
 */
@RestController
@RequestMapping("resource")
public class ResourceController {
    private final ResourceService resourceService;

    public ResourceController(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    /**
     * 分页获取资源
     */
    @GetMapping("getResourcesByPage")
    public RespResult getResourcesByPage(@RequestParam("pageNum") Long pageNum,
                                         @RequestParam("pageSize") Long pageSize,
                                         @RequestParam("resourceName") String resourceName){
        Page<ResourceEntity> resources = resourceService.getResourcesByPage(pageNum, pageSize, resourceName);
        Gson gson = GsonUtil.googleGson();
        return RespResult.OK(gson.toJson(resources));
    }

    /**
     * 新增资源
     */
    @PostMapping("insertResource")
    public RespResult insertResource(@RequestBody ResourceEntity resourceEntity){
        boolean flag = resourceService.insertResource(resourceEntity);
        return flag ? RespResult.OK() : RespResult.Fail();
    }

    /**
     * 删除资源
     */
    @GetMapping("deleteResourceById")
    public RespResult deleteResourceById(@RequestParam("id") Long id){
        boolean flag = resourceService.removeById(id);
        return flag ? RespResult.OK() : RespResult.Fail();
    }

    /**
     * 修改资源
     */
    @PostMapping("updateResourceById")
    public RespResult updateResourceById(@RequestBody ResourceEntity resourceEntity){
        boolean flag = resourceService.updateById(resourceEntity);
        return flag ? RespResult.OK() : RespResult.Fail();
    }

    /**
     * 获取所有的资源
     */
    @GetMapping("getAllResources")
    public RespResult getAllResources(){
        List<ResourceEntity> list = resourceService.list();
        Gson gson = GsonUtil.googleGson();
        return RespResult.OK(gson.toJson(list));
    }
}
